import { Modal, Toast } from 'antd-mobile';
import { remoteLinkAddress } from './ip';
import { ENTER_TYPE } from './Enum';
import * as dd from 'dingtalk-jsapi';
import createMemoryHistory from 'history/createMemoryHistory'
import router from 'umi/router';
//创建
const { alert } = Modal;
export function createTheURL(modelAPI, interfaceType) {
	const temp = modelAPI.split('');
	if (temp[temp.length - 1] !== '/') {
		temp.push('/');
	}
	const baseURL = remoteLinkAddress();
	const IP = baseURL + temp.join('') + interfaceType;
	return IP;
}

export function _arrayBufferToBase64(buffer) {
	var binary = '';
	var bytes = new Uint8Array(buffer);
	var len = bytes.byteLength;
	for (var i = 0; i < len; i++) {
		binary += String.fromCharCode(bytes[i]);
	}
	return 'data:application/pdf;base64,' + window.btoa(binary);
}
export function getSession() {
	const session = localStorage.getItem("Session");
	return session
}
export function checkUrl(query) {
	const { Session, enterType } = query
	// 用session判断是否同一次登陆，如果不是则清空localstorage
	const lastSession = localStorage.getItem('Session');
	if (enterType) {
		if (lastSession && lastSession !== Session && enterType == ENTER_TYPE.EXTERNAL) {
			// localStorage.clear();
			localStorage.setItem('enterHistoryNum', '');
			localStorage.setItem('isEnterPage', '')
		}
	}
	if (Object.keys(query).length === 2 && Session !== '' && localStorage.getItem('returnUrl') && enterType == ENTER_TYPE.EXTERNAL) {
		localStorage.setItem("Session", Session);
		localStorage.setItem('enterType', enterType);
		// localStorage.setItem('returnUrl',url);
		return true
	} else if (localStorage.getItem('Session') && localStorage.getItem('returnUrl') && localStorage.getItem('enterType') === ENTER_TYPE.EXTERNAL) {
		return true
	} else if (localStorage.getItem('enterType') === ENTER_TYPE.INTERIOR) {
		return true
	} else {
		return false
	}
}


export function isDingTalk() {
	const userAgent = window.navigator.userAgent.toLowerCase();
	return userAgent.indexOf('dingtalk') > -1 || false;
}

export function getIsDingTalk() {
	return localStorage.getItem('isDingTalk')
}

//记录返回页在history里的位置编号
export function recordEnterHistoryNum() {
	const enterHistoryNum = window.history.length - 1;
	localStorage.setItem('enterHistoryNum', enterHistoryNum)
	localStorage.setItem('isEnterPage', 'no');
}

export function backToOut() {
	const History = createMemoryHistory();
	const isDingTalk = localStorage.getItem('isDingTalk');
	const enterHistoryNum = localStorage.getItem("enterHistoryNum");
	const haveToAlipay = localStorage.getItem("haveToAlipay");
	const returnUrl = localStorage.getItem("returnUrl");
	const historyLength = sessionStorage.getItem('historyLen') || '';

	if (isDingTalk === 'true') {
		// if(historyLength==='0'||historyLength===''||historyLength==='NaN'||Number(historyLength)<0){
		//   window.history.go(-1);
		// }
		// else{
		//   window.history.go(0-Number(historyLength));
		// }
		dd.biz.navigation.close()
		sessionStorage.removeItem('historyLen');

		if (dd.env.platform !== "notInDingTalk") {
			dd.biz.navigation.setLeft({
				control: false,//是否控制点击事件，true 控制，false 不控制， 默认false
				text: '',//控制显示文本，空字符串表示显示默认文本
				onSuccess: function (result) {
				},
				onFail: function (err) {
				}

			});
			// }
		}
	}
	else {
		window.location.replace(returnUrl);
	}

	// localStorage.setItem('nextUrl','');
	localStorage.setItem('bizNo', '');
	localStorage.setItem('Certification', '');
	localStorage.setItem('status', '');
	localStorage.setItem('isSuccess', '')
	localStorage.setItem('Contact', '');
	localStorage.setItem('Captcha', '');
	localStorage.removeItem('currentPath')

}

export function checkAlipay(scheme) {
	var isBlur = false;
	// 通过URL scheme来调起APP
	location.href = scheme;
	let checkTime = setTimeout(function () {
		if (!isBlur) {
			alert('提示', '请检查是否安装支付宝或者关闭应用再试一次！', [
				{ text: '确认', onPress: () => { } },
			])
		}
	}, 3000);
	// window 每次失去焦點
	window.onblur = function () {
		isBlur = true;
	};
	var hiddenProperty = 'hidden' in document ? 'hidden' :
		'webkitHidden' in document ? 'webkitHidden' :
			'mozHidden' in document ? 'mozHidden' :
				null;
	var visibilityChangeEvent = hiddenProperty.replace(/hidden/i, 'visibilitychange');
	var onVisibilityChange = function () {
		if (document[hiddenProperty]) {
			isBlur = true;
			clearTimeout(checkTime);
		}
	}
	document.addEventListener(visibilityChangeEvent, onVisibilityChange);
}

export function dingCloseWindow(isSuccess) {
	let isDingTalk = localStorage.getItem('isDingTalk');
	if (isDingTalk === 'true') {
		if (dd.env.platform !== "notInDingTalk") {
			dd.biz.navigation.close({
				onSuccess: function () {
					if (isSuccess) {
						localStorage.setItem('isSuccess', 'true')
					}
					else {
						localStorage.setItem('isSuccess', 'false')
					}
					console.log('关闭窗口成功')
				},
				onFail: function (err) {
					console.log('关闭窗口失败')
				}
			})

		}
	}
}

export function showDingTalkHead() {
	let isDingTalk = localStorage.getItem('isDingTalk');
	if (isDingTalk === 'true') {
		if (dd.env.platform !== "notInDingTalk") {
			dd.biz.navigation.hideBar({
				hidden: false,// true：隐藏，false：显示
				onSuccess: function (result) {
				},
				onFail: function (err) { }
			})
		}
	}
}

export function hideDingTalkHead() {
	let isDingTalk = localStorage.getItem('isDingTalk');
	if (isDingTalk === 'true') {
		if (dd.env.platform !== "notInDingTalk") {
			dd.biz.navigation.hideBar({
				hidden: true,// true：隐藏，false：显示
				onSuccess: function (result) {

				},
				onFail: function (err) { }
			})
		}
	}

}

export function dingTalkBack(url) {
	let isDingTalk = localStorage.getItem('isDingTalk');
	if (isDingTalk === 'true') {
		if (dd.env.platform !== "notInDingTalk") {
			//进行钉钉登录操作
			dd.biz.navigation.replace({
				url: url,// 新的页面链接
				onSuccess: function (result) {
					console.log(result)
				}
			});
			//横屏
			// dd.device.screen.rotateView({
			//   showStatusBar : true, // 否显示statusbar
			//   clockwise : true, // 是否顺时针方向
			//   onSuccess : function(result) {
			//     console.log('成功',result)
			//   },
			//   onFail : function(err) {
			//     console.log('失败',err)}
			// });
		}

	}
}

export function dingTalkTitle(value) {
	let isDingTalk = localStorage.getItem('isDingTalk');
	if (isDingTalk === 'true') {
		if (dd.env.platform !== "notInDingTalk") {
			dd.biz.navigation.setTitle({
				title: value,
				onSuccess: function (result) {
					/*结构
					{
					}*/
				},
				onFail: function (err) { }
			});
		}
	}
}

export function closeTheCurrentPage() {
	let isDingTalk = localStorage.getItem('isDingTalk');
	if (isDingTalk === 'true') {
		if (dd.env.platform !== "notInDingTalk") {
			//进行钉钉登录操作
			dd.biz.navigation.goBack({
				onSuccess: function (result) {
					// router.push({
					//   pathname: '/Signature',
					//   query:{
					//     result:'success'
					//   },
					//   params: {
					//     type:'WRITE_SIGN',
					//   }
					// })
				},
				onFail: function (err) { }
			})
		}

	}

}



export function isAndroidOrIos() {
	var u = navigator.userAgent;
	if (u.indexOf("Android") > -1 || u.indexOf("Linux") > -1) {
		if (window.ShowFitness !== undefined) return 'Android';
	}
	if (u.indexOf("iPhone") > -1 || u.indexOf("iOS") > -1) {
		return 'iPhone';
	}
}


export function openUser(userId, corpId, name = 'profile') {
	const params = {
		id: userId,
		corpId: corpId
	}
	dd.ready(() => {
		dd.biz.util.open({
			name,
			params,
			onSuccess: (res) => {
				console.log(res)
			},
			onFail: (err) => {
				console.log(err)
				Toast.fail('无法打开！')
			}
		})
	})
}
